<!DOCTYPE html>
<html lang="en">
  <head>
    <title>
        Java-framework-Spring-1-容器 - rulerLwx Blog
      </title>
        <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-transform" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no,email=no,adress=no">
    
    <meta name="theme-color" content="#000000" />
    
    <meta http-equiv="window-target" content="_top" />
    
    
    <meta name="description" content="依赖注入 程序中不用new对象，从spring容器中获取。 设值注入 为类中的字段注入值，通过setter方法设置值（所以要为字段定义setXxx" />
    <meta name="generator" content="Hugo 0.73.0 with theme pure" />
    <title>Java-framework-Spring-1-容器 - rulerLwx Blog</title>
    
    
    <link rel="stylesheet" href="https://rulerLwx.gitee.io/css/style.min.c4bc7071f132c964c2116bca53b392933f377e5ca7b7051ed245187c621a2d3e.css">
    
    <link rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/9.15.10/styles/github.min.css" async>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.css" async>
    <meta property="og:title" content="Java-framework-Spring-1-容器" />
<meta property="og:description" content="依赖注入 程序中不用new对象，从spring容器中获取。 设值注入 为类中的字段注入值，通过setter方法设置值（所以要为字段定义setXxx" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://rulerLwx.gitee.io/2019/08/java-framework-spring-1-%E5%AE%B9%E5%99%A8/" />
<meta property="article:published_time" content="2019-08-15T11:02:30+08:00" />
<meta property="article:modified_time" content="2019-08-15T11:02:30+08:00" />
<meta itemprop="name" content="Java-framework-Spring-1-容器">
<meta itemprop="description" content="依赖注入 程序中不用new对象，从spring容器中获取。 设值注入 为类中的字段注入值，通过setter方法设置值（所以要为字段定义setXxx">
<meta itemprop="datePublished" content="2019-08-15T11:02:30&#43;08:00" />
<meta itemprop="dateModified" content="2019-08-15T11:02:30&#43;08:00" />
<meta itemprop="wordCount" content="3463">



<meta itemprop="keywords" content="" /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Java-framework-Spring-1-容器"/>
<meta name="twitter:description" content="依赖注入 程序中不用new对象，从spring容器中获取。 设值注入 为类中的字段注入值，通过setter方法设置值（所以要为字段定义setXxx"/>

    <!--[if lte IE 9]>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
      <![endif]-->

    <!--[if lt IE 9]>
        <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
      <![endif]-->
  </head>

  
  

  <body class="main-center theme-black" itemscope itemtype="http://schema.org/WebPage"><header class="header" itemscope itemtype="http://schema.org/WPHeader">
    <div class="slimContent">
      <div class="navbar-header">
        <div class="profile-block text-center">
          <a id="avatar" href="https://gitee.com/rulerLwx" target="_blank">
            <img class="img-circle img-rotate" src="https://rulerLwx.gitee.io/avatar.png" width="200" height="200">
          </a>
          <h2 id="name" class="hidden-xs hidden-sm">rulerLwx</h2>
          <h3 id="title" class="hidden-xs hidden-sm hidden-md">thinking...</h3>
          <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i>Guangzhou, China</small>
        </div><div class="search" id="search-form-wrap">
    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="Search" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i
                        class="icon icon-search"></i></button>
            </span>
        </div>
        <div class="ins-search">
            <div class="ins-search-mask"></div>
            <div class="ins-search-container">
                <div class="ins-input-wrapper">
                    <input type="text" class="ins-search-input" placeholder="Type something..."
                        x-webkit-speech />
                    <button type="button" class="close ins-close ins-selectable" data-dismiss="modal"
                        aria-label="Close"><span aria-hidden="true">×</span></button>
                </div>
                <div class="ins-section-wrapper">
                    <div class="ins-section-container"></div>
                </div>
            </div>
        </div>
    </form>
</div>
        <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
      </div>
      <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
        <ul class="nav navbar-nav main-nav">
            <li class="menu-item menu-item-home">
                <a href="/">
                    <i class="icon icon-home-fill"></i>
                  <span class="menu-title">Home</span>
                </a>
            </li>
            <li class="menu-item menu-item-archives">
                <a href="/posts/">
                    <i class="icon icon-archives-fill"></i>
                  <span class="menu-title">Archives</span>
                </a>
            </li>
            <li class="menu-item menu-item-categories">
                <a href="/categories/">
                    <i class="icon icon-folder"></i>
                  <span class="menu-title">Categories</span>
                </a>
            </li>
            <li class="menu-item menu-item-tags">
                <a href="/tags/">
                    <i class="icon icon-tags"></i>
                  <span class="menu-title">Tags</span>
                </a>
            </li>
            <li class="menu-item menu-item-about">
                <a href="/about/">
                    <i class="icon icon-cup-fill"></i>
                  <span class="menu-title">About</span>
                </a>
            </li>
        </ul>
      </nav>
    </div>
  </header>

<aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">Board</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">enjoy~
            </div>
        </div>
    </div>
</div>

      <div class="widget">
    <h3 class="widget-title"> Categories</h3>
    <div class="widget-body">
        <ul class="category-list">
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-framework/" class="category-list-link">java-framework</a><span class="category-list-count">38</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-front-end/" class="category-list-link">java-front-end</a><span class="category-list-count">11</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-se/" class="category-list-link">java-se</a><span class="category-list-count">21</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-senior/" class="category-list-link">java-senior</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/linux/" class="category-list-link">linux</a><span class="category-list-count">13</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/tools/" class="category-list-link">tools</a><span class="category-list-count">1</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%8A%80%E6%9C%AF%E6%9D%82%E7%83%A9/" class="category-list-link">技术杂烩</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" class="category-list-link">数据库</a><span class="category-list-count">15</span></li>
        </ul>
    </div>
</div>
      <div class="widget">
    <h3 class="widget-title"> Tags</h3>
    <div class="widget-body">
        <ul class="tag-list">
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/jvm/" class="tag-list-link">jvm</a><span
                    class="tag-list-count">1</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" class="tag-list-link">多线程</a><span
                    class="tag-list-count">2</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" class="tag-list-link">网络编程</a><span
                    class="tag-list-count">3</span></li>
            
        </ul>

    </div>
</div>
      
<div class="widget">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget-body">
        <ul class="recent-post-list list-unstyled no-thumbnail">
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%87%AA%E5%B7%B1%E5%8A%A8%E6%89%8B%E4%B8%80%E6%89%B9%E9%87%8F%E7%A7%BB%E5%8A%A8%E9%87%8D%E5%91%BD%E5%90%8D%E6%96%87%E4%BB%B6/" class="title">自己动手（一）——批量移动、重命名文件</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-27 17:50:02 &#43;0800 CST" itemprop="datePublished">2020-07-27</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E5%85%B3%E4%BA%8Einteger%E7%9A%84-128~127%E7%BC%93%E5%AD%98/" class="title">关于Integer的 -128~127缓存</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-11 16:56:21 &#43;0800 CST" itemprop="datePublished">2020-07-11</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98/" class="title">跨域问题</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-08 22:41:12 &#43;0800 CST" itemprop="datePublished">2020-07-08</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E4%B8%AA%E4%BA%BA%E5%8D%9A%E5%AE%A2%E6%90%AD%E5%BB%BA/" class="title">个人博客搭建</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-05 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-05</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/mongodb-1/" class="title">MonggoDB-1</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-03 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-03</time>
                    </p>
                </div>
            </li>
        </ul>
    </div>
</div>
  </div>
</aside>

    
    
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <h4 class="toc-title">Catalogue</h4>
    <nav id="toc" class="js-toc toc">

    </nav>
  </div>
</aside>
<main class="main" role="main"><div class="content">
  <article id="-" class="article article-type-" itemscope
    itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      <h1 itemprop="name">
  <a
    class="article-title"
    href="/2019/08/java-framework-spring-1-%E5%AE%B9%E5%99%A8/"
    >Java-framework-Spring-1-容器</a
  >
</h1>

      <div class="article-meta">
        
<span class="article-date">
  <i class="icon icon-calendar-check"></i>&nbsp;
<a href="https://rulerLwx.gitee.io/2019/08/java-framework-spring-1-%E5%AE%B9%E5%99%A8/" class="article-date">
  <time datetime="2019-08-15 11:02:30 &#43;0800 CST" itemprop="datePublished">2019-08-15</time>
</a>
</span>
<span class="article-category">
  <i class="icon icon-folder"></i>&nbsp;
  <a class="article-category-link" href="/categories/java-framework/"> Java-framework </a>
</span>

        <span class="post-comment"><i class="icon icon-comment"></i>&nbsp;<a href="/2019/08/java-framework-spring-1-%E5%AE%B9%E5%99%A8/#comments"
            class="article-comment-link">Comments</a></span>
		<span class="post-wordcount hidden-xs" itemprop="wordCount">Word Count: 3463words</span>
		<span class="post-readcount hidden-xs" itemprop="timeRequired">Read Count: 7minutes </span>
      </div>
    </div>
    <div class="article-entry marked-body js-toc-content" itemprop="articleBody">
      <h1 id="依赖注入">依赖注入</h1>
<p>程序中不用new对象，从spring容器中获取。</p>
<h2 id="设值注入">设值注入</h2>
<p>为类中的字段注入值，通过setter方法设置值（所以要为字段定义setXxx方法）。</p>
<p>1、引用类型</p>
<pre><code>&lt;bean id=&quot;chinese&quot; class=&quot;org.crazyit.app.service.impl.Chinese&quot;&gt;
	&lt;property name=&quot;axe&quot; ref=&quot;stoneAxe&quot;/&gt;
&lt;/bean&gt;

&lt;bean id=&quot;stoneAxe&quot; class=&quot;org.crazyit.app.service.impl.StoneAxe&quot;/&gt;
</code></pre>
<p>2、普通属性值</p>
<pre><code>&lt;bean id=&quot;exampleBean&quot; class=&quot;org.crazyit.app.service.ExampleBean&quot;&gt;
	&lt;!-- 指定int型的参数值 --&gt;
	&lt;property name=&quot;integerField&quot; value=&quot;1&quot;/&gt;
	&lt;!-- 指定double型的参数值 --&gt;
	&lt;property name=&quot;doubleField&quot; value=&quot;2.3&quot;/&gt;
&lt;/bean&gt;
</code></pre>
<p>3、注入集合值</p>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;GBK&quot;?&gt;
&lt;beans xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns=&quot;http://www.springframework.org/schema/beans&quot;
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd&quot;&gt;
	
	&lt;bean id=&quot;stoneAxe&quot; class=&quot;org.crazyit.app.service.impl.StoneAxe&quot;/&gt;
	&lt;bean id=&quot;steelAxe&quot; class=&quot;org.crazyit.app.service.impl.SteelAxe&quot;/&gt;
	
	&lt;bean id=&quot;chinese&quot; class=&quot;org.crazyit.app.service.impl.Chinese&quot;&gt;
		&lt;property name=&quot;schools&quot;&gt;
			&lt;!-- 为调用setSchools()方法配置List集合作为参数值 --&gt;
			&lt;list&gt;
				&lt;!-- 每个value、ref、bean...都配置一个List元素 --&gt;
				&lt;value&gt;小学&lt;/value&gt;
				&lt;value&gt;中学&lt;/value&gt;
				&lt;value&gt;大学&lt;/value&gt;
			&lt;/list&gt;
		&lt;/property&gt;
		&lt;property name=&quot;scores&quot;&gt;
			&lt;!-- 为调用setScores()方法配置Map集合作为参数值 --&gt;
			&lt;map&gt;
				&lt;!-- 每个entry配置一个key-value对 --&gt;
				&lt;entry key=&quot;数学&quot; value=&quot;87&quot;/&gt;
				&lt;entry key=&quot;英语&quot; value=&quot;89&quot;/&gt;
				&lt;entry key=&quot;语文&quot; value=&quot;82&quot;/&gt;
			&lt;/map&gt;
		&lt;/property&gt;
		&lt;property name=&quot;phaseAxes&quot;&gt;
			&lt;!-- 为调用setPhaseAxes()方法配置Map集合作为参数值 --&gt;
			&lt;map&gt;
				&lt;!-- 每个entry配置一个key-value对 --&gt;
				&lt;entry key=&quot;原始社会&quot; value-ref=&quot;stoneAxe&quot;/&gt;
				&lt;entry key=&quot;农业社会&quot; value-ref=&quot;steelAxe&quot;/&gt;
			&lt;/map&gt;
		&lt;/property&gt;
		&lt;property name=&quot;health&quot;&gt;
			&lt;!-- 为调用setHealth()方法配置Properties集合作为参数值 --&gt;
			&lt;props&gt;
				&lt;!-- 每个prop元素配置一个属性项，其中key指定属性名 --&gt;
				&lt;prop key=&quot;血压&quot;&gt;正常&lt;/prop&gt;
				&lt;prop key=&quot;身高&quot;&gt;175&lt;/prop&gt;
			&lt;/props&gt;
			&lt;!-- 
			&lt;value&gt;
				pressure=normal
				height=175
			&lt;/value&gt; --&gt;
		&lt;/property&gt;
		&lt;property name=&quot;axes&quot;&gt;
			&lt;!-- 为调用setAxes()方法配置Set集合作为参数值 --&gt;
			&lt;set&gt;
				&lt;!-- 每个value、ref、bean..都配置一个Set元素 --&gt;
				&lt;value&gt;普通的字符串&lt;/value&gt;
				&lt;bean class=&quot;org.crazyit.app.service.impl.SteelAxe&quot;/&gt;
				&lt;ref bean=&quot;stoneAxe&quot;/&gt;
				&lt;!-- 为Set集合配置一个List集合作为元素 --&gt;
				&lt;list&gt;
					&lt;value&gt;20&lt;/value&gt;
					&lt;!-- 再次为List集合配置一个Set集合作为元素 --&gt;
					&lt;set&gt;
						&lt;value type=&quot;int&quot;&gt;30&lt;/value&gt;
					&lt;/set&gt;
				&lt;/list&gt;
			&lt;/set&gt;
		&lt;/property&gt;
		&lt;property name=&quot;books&quot;&gt;
			&lt;!-- 为调用setBooks()方法配置数组作为参数值 --&gt;
			&lt;list&gt;
				&lt;!-- 每个value、ref、bean...都配置一个数组元素 --&gt;
				&lt;value&gt;疯狂Java讲义&lt;/value&gt;
				&lt;value&gt;疯狂Android讲义&lt;/value&gt;
				&lt;value&gt;轻量级Java EE企业应用实战&lt;/value&gt;
			&lt;/list&gt;
		&lt;/property&gt;
	&lt;/bean&gt;
&lt;/beans&gt;
</code></pre>
<p>4、组合属性</p>
<p><code>&lt;property name=&quot;person.name&quot; value=&quot;孙悟空&quot;/&gt;</code></p>
<p>为属性设计setter方法，是个不错的选择。（新的spring版本好像不用？？？？）</p>
<p>答：“零配置”则不用写setter方法，xml的配置方式，则要写。</p>
<h2 id="构造注入">构造注入</h2>
<p>通过构造器参数为字段注入值。</p>
<p>1、引用类型：</p>
<pre><code>&lt;bean id=&quot;chinese&quot; class=&quot;org.crazyit.app.service.impl.Chinese&quot;&gt;
	&lt;constructor-arg ref=&quot;steelAxe&quot; type=&quot;org.crazyit.app.service.Axe&quot;/&gt;
&lt;/bean&gt;

&lt;bean id=&quot;steelAxe&quot; class=&quot;org.crazyit.app.service.impl.SteelAxe&quot;/&gt;
</code></pre>
<p>2、基本类型或String类型，可以直接赋值，不用ref属性了：</p>
<pre><code>&lt;bean id=&quot;chinese&quot; class=&quot;org.crazyit.app.service.impl.Chinese&quot;&gt;
	&lt;constructor-arg value=”hello”/&gt;
	&lt;constructor-arg value=”123”/&gt;
&lt;/bean&gt;
</code></pre>
<p>也可以为上面的元素指定type属性，指定类型。</p>
<h1 id="spring容器">Spring容器</h1>
<ul>
<li>
<p>Java Se常用的容器：</p>
<p>FileSystemXmlApplicationContext、ClassPathXmlApplicationContext、AnnotationConfigApplicationContext。</p>
</li>
<li>
<p>Java Web常用的容器：</p>
<p>XmlWebApplicationContext、AnnotationConfigWebApplicationContext。</p>
</li>
</ul>
<p>创建容器示例：</p>
<pre><code>ApplicationContext ctx = new FileSystemXmlApplicationContext(&quot;beans.xml&quot;,&quot;service.xml&quot;);
ApplicationContext ctx = new ClassPathXmlApplicationContext(&quot;beans.xml&quot;,&quot;service.xml&quot;);
</code></pre>
<p>在容器启动时，默认自动创建singleton bean。</p>
<h2 id="applicationcontext事件机制">ApplicationContext事件机制</h2>
<p>ApplicationContext事件机制是观察者设计模式的实现。有如下两个重要成员：</p>
<ul>
<li>ApplicationEvent：容器事件，必须由ApplicationContext发布。</li>
<li>ApplicationListener：监听器，可由容器中任意监听器Bean担任。</li>
</ul>
<p>每当ApplicationContext发布ApplicationEvent时，ApplicationListener Bean将自动触发（onApplicationEvent(ApplicationEvent event)被调用）。</p>
<p>事件的三个要素：</p>
<ul>
<li>事件源：ApplicationContext</li>
<li>事件：ApplicationEvent</li>
<li>监听器：ApplicationListener</li>
</ul>
<p>示例：</p>
<pre><code>public class EmailEvent extends ApplicationEvent
{
	private String address;
	private String text;

	public EmailEvent(Object source)
	{
		super(source);
	}
	
	// 初始化全部成员变量的构造器
	public EmailEvent(Object source , String address , String text)
	{
		super(source);
		this.address = address;
		this.text = text;
	}

	public void setAddress(String address)
	{
		this.address = address;
	}
	public String getAddress()
	{
		return this.address;
	}

	public void setText(String text)
	{
		this.text = text;
	}
	public String getText()
	{
		return this.text;
	}
}
</code></pre>
<pre><code>public class EmailNotifier implements ApplicationListener
{
	// 该方法会在容器发生事件时自动触发
	public void onApplicationEvent(ApplicationEvent evt)
	{
		// 只处理EmailEvent，模拟发送email通知...
		if (evt instanceof EmailEvent)
		{
			EmailEvent emailEvent = (EmailEvent)evt;
			System.out.println(&quot;需要发送邮件的接收地址 &quot; + emailEvent.getAddress());
			System.out.println(&quot;需要发送邮件的邮件正文 &quot; + emailEvent.getText());
		}
		else
		{
			// 其他事件不作任何处理
			System.out.println(&quot;其他事件：&quot; + evt);
		}
	}
}
</code></pre>
<p>beans.xml</p>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;GBK&quot;?&gt;
&lt;beans xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns=&quot;http://www.springframework.org/schema/beans&quot;
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd&quot;&gt;
	&lt;!-- 配置监听器 --&gt;
	&lt;bean class=&quot;org.crazyit.app.listener.EmailNotifier&quot;/&gt;
&lt;/beans&gt;
</code></pre>
<pre><code>public class SpringTest
{
	public static void main(String[] args)
	{
		ApplicationContext ctx = new ClassPathXmlApplicationContext(&quot;beans.xml&quot;);
		// 创建一个ApplicationEvent对象
		EmailEvent ele = new EmailEvent(&quot;test&quot; ,&quot;spring_test@163.com&quot; , &quot;this is a test&quot;);
		// 发布容器事件
		ctx.publishEvent(ele);
	}
}
</code></pre>
<p>首先要实现ApplicationListener接口，并交给spring管理（相当于注册一个监听器）。</p>
<h2 id="让bean获取spring容器">让Bean获取Spring容器</h2>
<p>在web开发中，不可能手动创建spring容器，有如下两种方法获取spring容器：</p>
<ul>
<li>实现BeanFactoryAware接口，重写setBeanFactory(BeanFactory beanFactory)方法，其中beanFactory就是spring容器了</li>
<li>实现ApplicationContextAware接口，重写setApplicationContext(ApplicationContext applicationContext)方法，其中applicationContext就是spring容器了。</li>
</ul>
<h2 id="创建bean的三种方式">创建Bean的三种方式</h2>
<h3 id="构造器创建bean实例">构造器创建Bean实例</h3>
<p>这种方式就是前面介绍的构造注入的方式。class属性指定的就是Bean实例的实现类。</p>
<h3 id="静态工厂方法创建bean实例">静态工厂方法创建Bean实例</h3>
<p>使用静态工厂方法创建bean时，&lt;bean &hellip;/&gt;元素的需要指定class属性、factory-method属性：</p>
<ul>
<li>class：该属性的值为静态工厂类的类名</li>
<li>factory-method：该属性指定静态工厂方法来生产Bean实例</li>
</ul>
<p>如果静态工厂方法需要参数，则使用&lt;constructor-arg&hellip;/&gt;元素传入。</p>
<p>示例：</p>
<pre><code>public interface Being
{
	public void testBeing();
}
</code></pre>
<pre><code>public class Dog implements Being
{
	private String msg;
	public void setMsg(String msg)
	{
		this.msg = msg;
	}
	
	public void testBeing()
	{
		System.out.println(msg +	&quot;，狗爱啃骨头&quot;);
	}
}
</code></pre>
<pre><code>public class Cat implements Being
{
	private String msg;
	public void setMsg(String msg)
	{
		this.msg = msg;
	}
	
	public void testBeing()
	{
		System.out.println(msg +	&quot;，猫喜欢吃老鼠&quot;);
	}
}
</code></pre>
<pre><code>public class BeingFactory
	public static Being getBeing(String arg)
	{
		if (arg.equalsIgnoreCase(&quot;dog&quot;))
		{
			return new Dog();
		}else
		{
			return new Cat();
		}
	}
}
</code></pre>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;GBK&quot;?&gt;
&lt;beans xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns=&quot;http://www.springframework.org/schema/beans&quot;
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd&quot;&gt;

    &lt;!--下面代码相当于 dog = org.crazyit.app.factory.BeingFactory.getBeing(&quot;dog&quot;);--&gt;
    
	&lt;bean id=&quot;dog&quot; class=&quot;org.crazyit.app.factory.BeingFactory&quot; factory-method=&quot;getBeing&quot;&gt;
		&lt;constructor-arg value=&quot;dog&quot;/&gt;
		&lt;property name=&quot;msg&quot; value=&quot;我是狗&quot;/&gt;
	&lt;/bean&gt;
	
	&lt;bean id=&quot;cat&quot; class=&quot;org.crazyit.app.factory.BeingFactory&quot; factory-method=&quot;getBeing&quot;&gt;
		&lt;constructor-arg value=&quot;cat&quot;/&gt;
		&lt;property name=&quot;msg&quot; value=&quot;我是猫&quot;/&gt;
	&lt;/bean&gt;
&lt;/beans&gt;
</code></pre>
<pre><code>public class SpringTest
{
	public static void main(String[] args)
	{
		ApplicationContext ctx = new ClassPathXmlApplicationContext(&quot;beans.xml&quot;);
		
		Being b1 = ctx.getBean(&quot;dog&quot; , Being.class);
		b1.testBeing();
		
		Being b2 = ctx.getBean(&quot;cat&quot; , Being.class);
		b2.testBeing();
	}
}
</code></pre>
<h3 id="实例工厂方法创建bean实例">实例工厂方法创建Bean实例</h3>
<p>使用实例工厂方法创建bean时，&lt;bean &hellip;/&gt;元素需要指定如下两个属性：</p>
<ul>
<li>factory-bean：该属性值为工厂Bean的id。</li>
<li>factory-method：该属性指定实例工厂的工厂方法。</li>
</ul>
<p>如果实例工厂方法需要参数，则使用&lt;constructor-arg&hellip;/&gt;元素传入。</p>
<p>示例：</p>
<pre><code>public interface Person
{
	public String sayHello(String name);
	public String sayGoodBye(String name);
}
</code></pre>
<pre><code>public class American implements Person
{
	public String sayHello(String name){
		return name + &quot;,Hello!&quot;;
	}
	public String sayGoodBye(String name){
		return name + &quot;,Good Bye!&quot;;
	}
}
</code></pre>
<pre><code>public class Chinese implements Person
{
	public String sayHello(String name){
		return name + &quot;，您好&quot;;
	}
	public String sayGoodBye(String name)	{
		return name + &quot;，下次再见&quot;;
	}
}
</code></pre>
<pre><code>public class PersonFactory
{
	public Person getPerson(String ethnic)
	{
		if (ethnic.equalsIgnoreCase(&quot;chin&quot;)){
			return new Chinese();
		}else{
			return new American();
		}
	}
}
</code></pre>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;GBK&quot;?&gt;
&lt;beans xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns=&quot;http://www.springframework.org/schema/beans&quot;
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd&quot;&gt;
	
	&lt;bean id=&quot;personFactory&quot; class=&quot;org.crazyit.app.factory.PersonFactory&quot;/&gt;
	
	&lt;bean id=&quot;chinese&quot; factory-bean=&quot;personFactory&quot;	factory-method=&quot;getPerson&quot;&gt;
		&lt;constructor-arg value=&quot;chin&quot;/&gt;
	&lt;/bean&gt;
	
	&lt;bean id=&quot;american&quot; factory-bean=&quot;personFactory&quot; factory-method=&quot;getPerson&quot;&gt;
		&lt;constructor-arg value=&quot;ame&quot;/&gt;
	&lt;/bean&gt;
&lt;/beans&gt;
</code></pre>
<pre><code>public class SpringTest
{
	public static void main(String[] args)
	{
		ApplicationContext ctx = new ClassPathXmlApplicationContext(&quot;beans.xml&quot;);
		
		Person p1 = ctx.getBean(&quot;chinese&quot;, Person.class);
		System.out.println(p1.sayHello(&quot;Mary&quot;));
		System.out.println(p1.sayGoodBye(&quot;Mary&quot;));
		
		Person p2 = ctx.getBean(&quot;american&quot;, Person.class);
		System.out.println(p2.sayHello(&quot;Jack&quot;));
		System.out.println(p2.sayGoodBye(&quot;Jack&quot;));
	}
}
</code></pre>
<p>总结：实例工厂方法与静态工厂方法的不同之处是，生产实例的不指向一个工厂类，而是指向一个工厂的实例（因为在配置工厂方法的前已经配置了一个工厂bean，直接使用这个bean）。</p>

    </div>
    <div class="article-footer">
<blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    <li class="post-copyright-link hidden-xs">
      <strong>Permalink: </strong>
      <a href="https://rulerLwx.gitee.io/2019/08/java-framework-spring-1-%E5%AE%B9%E5%99%A8/" title="Java-framework-Spring-1-容器" target="_blank" rel="external">https://rulerLwx.gitee.io/2019/08/java-framework-spring-1-%E5%AE%B9%E5%99%A8/</a>
    </li>
    <li class="post-copyright-license">
      <strong>License：</strong><a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN</a>
    </li>
  </ul>
</blockquote>

<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://gitee.com/rulerLwx" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="https://rulerLwx.gitee.io/avatar.png" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://gitee.com/rulerLwx" target="_blank"><span class="text-dark">rulerLwx</span><small class="ml-1x">thinking...</small></a></h3>
        <div>Good Good Study, Day Day Up~</div>
      </div>
    </figure>
  </div>
</div>
    </div>
  </article>
<section id="comments">
    <div id="vcomments"></div>
</section>

</div><nav class="bar bar-footer clearfix" data-stick-bottom>
    <div class="bar-inner">
        <ul class="pager pull-left">
            <li class="prev">
                <a href="https://rulerLwx.gitee.io/2019/08/java-framework-shiro/" title="Java-framework-Shiro"><i
                        class="icon icon-angle-left"
                        aria-hidden="true"></i><span>&nbsp;&nbsp;Older</span></a>
            </li>
            <li class="next">
                <a href="https://rulerLwx.gitee.io/2019/08/java-framework-spring-2-%E5%AE%B9%E5%99%A8/"
                    title="Java-framework-Spring-2-容器"><span>Newer&nbsp;&nbsp;</span><i
                        class="icon icon-angle-right" aria-hidden="true"></i></a>
            </li>
            
            <li class="toggle-toc">
                <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false"
                    title="Catalogue" role="button">
                    <span>[&nbsp;</span><span>Catalogue</span>
                    <i class="text-collapsed icon icon-anchor"></i>
                    <i class="text-in icon icon-close"></i>
                    <span>]</span>
                </a>
            </li>
        </ul>
        <div class="bar-right">
            <div class="share-component" data-sites="weibo,qq,wechat"
                data-mobile-sites="weibo,qq,qzone"></div>
        </div>
    </div>
</nav>

</main><footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
<ul class="social-links">
    <li><a href="https://gitee.com/rulerLwx" target="_blank" title="gitee" data-toggle=tooltip data-placement=top >
            <i class="icon icon-gitee"></i></a></li>
    <li><a href="https://github.com/wolf-lea" target="_blank" title="github" data-toggle=tooltip data-placement=top >
            <i class="icon icon-github"></i></a></li>
</ul>
  <div class="copyright">
    &copy;2017  -
    2020
    <div class="publishby">
        Theme by <a href="https://github.com/xiaoheiAh" target="_blank"> xiaoheiAh </a>base on<a href="https://github.com/xiaoheiAh/hugo-theme-pure" target="_blank"> pure</a>.
    </div>
  </div>
</footer>

<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_SVG"></script>
<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
            showMathMenu: false, //disables context menu
            tex2jax: {
            inlineMath: [ ['$','$'], ['\\(','\\)'] ]
           }
    });
</script>


<script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>
<script>
    window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/highlight.min.js"></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/python.min.js" defer></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/javascript.min.js" defer></script><script>
    hljs.configure({
        tabReplace: '    ', 
        classPrefix: ''     
        
    })
    hljs.initHighlightingOnLoad();
</script>
<script src="https://rulerLwx.gitee.io/js/application.min.bdeb64b910570b6c41badc6a05b7afb0c8ad9efd8525de3c7257d59e786326a3.js"></script>
<script src="https://rulerLwx.gitee.io/js/plugin.min.51ff8c7317566f82259170fa36e09c4493adc9b9378b427a01ad3f017ebac7dd.js"></script>

<script>
    (function (window) {
        var INSIGHT_CONFIG = {
            TRANSLATION: {
                POSTS: 'Posts',
                PAGES: 'Pages',
                CATEGORIES: 'Categories',
                TAGS: 'Tags',
                UNTITLED: '(Untitled)',
            },
            ROOT_URL: 'https:\/\/rulerLwx.gitee.io',
            CONTENT_URL: 'https:\/\/rulerLwx.gitee.io\/searchindex.json ',
        };
        window.INSIGHT_CONFIG = INSIGHT_CONFIG;
    })(window);
</script>
<script type="text/javascript" src="https://rulerLwx.gitee.io/js/insight.min.a343cd9a5a7698336b28ef3a7c16a3a1b1d2d5fb17dc8ed04022bbe08cc5459073a15bdafa3a8a58cdd56080784bdd69fa70b1ae8597565c799c57ed00f0e120.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.min.js"></script>
<script>
    tocbot.init({
        
        tocSelector: '.js-toc',
        
        contentSelector: '.js-toc-content',
        
        headingSelector: 'h1, h2, h3',
        
        hasInnerContainers: true,
    });
</script>

<script src="https://cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine"></script>
<script type="text/javascript">
    var GUEST = ['nick', 'mail', 'link'];
    var meta = 'nick,mail';
    meta = meta.split(',').filter(function (item) {
        return GUEST.indexOf(item) > -1;
    });
    new Valine({
        el: '#vcomments',
        verify: null ,
        notify: null ,
        appId: 'IyAB0PSPRazTPDxitO1ddQ7O-gzGzoHsz',
        appKey: '5rBJTq4KidYF33eXwvRVhtEH',
        placeholder: 'enjoy~',
        avatar: 'mm',
        meta: meta,
        pageSize: '10' || 10,
        visitor: false 
});
</script>

  </body>
</html>
